<template>
  <view>111</view>
</template>
<script setup>
import {
  computed,
  nextTick,
  ref,
  watch,
  reactive,
  getCurrentInstance,
  onMounted,
} from "vue";
import {
  GetOrderListApi,
  GetUpdateOrderStatusApi,
  AddOrderAmountApi,
  cancelOrderByOrderId,
  ConfirmPaymentApi,
  RaisePriceApi,
  GetMsgReadDotApi,
  GetInformReadDotApi,
  GetOrderIsUploadImg,
} from "@/api/modules/orders.js";
import { onShow, onReachBottom, onLoad } from "@dcloudio/uni-app";
import dayjs from "dayjs";
import { copy, checkStr } from "@/utils/index.js";
import { getTitleBarHeight } from "@/utils/system.js";
import Md5 from "js-md5";

import useStore from "@/stores";

const { globalStore } = useStore();
import {
  formateStr,
  isDesktopSafari,
  isRealName_SetPwd,
} from "@/utils/index.js";

const emit = defineEmits(["onKeyboardHeightChange"]);

const userInfo = globalStore.userInfo;
//
const orderLevel = computed(() => (data) => {
  const levelList = ["普通订单", "优质订单", "高级订单"];
  return levelList[data - 1];
});
//
const orderLevelImage = computed(() => (data) => {
  const orderLevelImage = [
    "/static/orders/low_logo.png",
    "/static/orders/middle_logo.png",
    "/static/orders/high_logo.png",
  ];
  return orderLevelImage[data - 1];
});
//
const isSpecificValue = (status) => {
  return [1, 8, 9, 10, 11, 12].includes(status);
};

// 状态 1-待支付 2-未接单 3-代练中 4-待验收 5-异常中 6-撤销中 7-仲裁中 8-已完成 9-撤销完成 10-仲裁完成 11-强制撤销 12-已取消
const orderType = computed(() => (data) => {
  const orderTypeList = [
    "待支付", //	待支付
    "未接单", //	未接单
    "代练中", //	代练中
    "待验收", //	待验收
    "异常中", //	异常中
    "撤销中", //	撤销中
    "仲裁中", //	仲裁中
    "已完成", //	已完成
    "撤销完成", //	撤销完成
    "仲裁完成", //	仲裁完成
    "强制撤销", //	强制撤销
    "已取消", //	已取消
  ];
  return orderTypeList[data - 1];
});

const initParams = reactive({
  type: 2,
  searchContent: "",
  status: 1,
  searchType: 1,
  creatorType: userInfo.isMerchant * 1 === 1 ? 1 : 2,
  isMerchant: globalStore.token
    ? globalStore.userInfo?.platform * 1 === 3
      ? globalStore.parentUserInfo.isMerchant
      : globalStore.userInfo.isMerchant
    : "",
});

const pickerRef = ref();
const dataList = ref([]);
const amountVal = ref();
const popupRef = ref();
const activeCurrent = ref(0);
const curIndex = ref(0); //tabsList2用的
const orderSelectRef = ref();
const orderStatus = ref(); // 订单状态
const orderId = ref();
const modalRef = ref();
const payPwd = ref();
const applyArbitrament = ref(); //申请仲裁发起方userid
const applyRepeal = ref(); //申请撤销发起方userid
const upStatus = ref(); //撤消记录
const modelType = ref("同意撤销"); //用于区分同意撤销和同意验收、加价,打赏打手
const afterCreateTime = ref();
const hatchetUserId = ref();
const compensation = ref();
const payVicarious = ref();
//
const props = defineProps({
  active: String,
  current: String,
  status: String,
});
const tabsList2 = computed(() => {
  let tablist = [];
  switch (initParams.type) {
    case 2:
      tablist = [
        {
          name: "全部",
          status: 1,
          index: 0,
        },
        {
          name: "代练中",
          status: 2,
          index: 1,
        },
        {
          name: "待验收",
          status: 3,
          index: 2,
        },
        {
          name: "售后中",
          status: 4,
          index: 3,
        },
        {
          name: "已完结",
          status: 5,
          index: 4,
        },
      ];
      break;
    case 3:
      tablist = [
        {
          name: "全部",
          status: 1,
          index: 0,
        },
        {
          name: "未接单",
          status: 6,
          index: 1,
        },
        {
          name: "代练中",
          status: 2,
          index: 2,
        },
        {
          name: "待验收",
          status: 3,
          index: 3,
        },
        {
          name: "售后中",
          status: 4,
          index: 4,
        },
        {
          name: "已完结",
          status: 5,
          index: 5,
        },
      ];
      break;
  }
  return tablist;
});
const tabsList = ref([
  {
    name: "接手订单",
    id: 2,
  },
  {
    name: "发布订单",
    id: 3,
  },
]);

// 是否展示免押权益标识
const getNoDepositStatus = (isNoDeposit) => {
  const shouldShow =
    (initParams.type === 2 && isNoDeposit === 2) ||
    (initParams.type === 3 && (isNoDeposit === 1 || isNoDeposit === 2));
  // 置灰
  const shouldGray =
    initParams.type === 3 && isNoDeposit === 1
      ? true
      : initParams.type === 3 && isNoDeposit === 2
      ? false
      : null;
  return {
    shouldShow,
    shouldGray,
  };
};

const ViewOrderDetail = (item) => {
  uni.navigateTo({
    url: `/pages_orders/order_details/index?active=${initParams.type}&status=${item.status}&afterCreateTime=${item.afterCreateTime}&orderId=${item.orderId}`,
  });
  onShowFlag.value = 0;
};

const handleActive = (type) => {
  if (globalStore.tabbarIdx === 4) {
    if (type.id === 2) {
      initParams.type = 2;
    } else {
      initParams.type = 3;
    }
    initParams.status = 1;
    curIndex.value = 0;
    scrollViewRef.value?.reloadData(initParams);
  }
};

const acceptParams = reactive({
  amount: "", //金额
  cashDeposit: "", // 保证金
});

const handleSearch = () => {
  scrollViewRef.value?.reloadData(initParams);
};

//加价
const handleAddPrice = (item) => {
  amountVal.value = "";
  payPwd.value = "";
  modelType.value = "加价";
  orderId.value = item.orderId;
  popupRef.value.open();
};

//去支付
const orderNo = ref();
const handleGoPay = (item) => {
  //是否实名  //是否设置密码
  if (!isRealName_SetPwd()) return;
  payPwd.value = "";
  modelType.value = "去支付";
  orderNo.value = item.orderNo;
  modalRef.value.open();
};

//打赏打手
const handleGive = (item) => {
  amountVal.value = "";
  payPwd.value = "";
  modelType.value = "打赏打手";
  orderId.value = item.orderId;
  orderNo.value = item.orderNo;
  popupRef.value.open();
};

//打开输入框
const submit = () => {
  const str = modelType.value === "打赏打手" ? "打赏" : "加价";
  if (amountVal.value * 1 === 0) {
    uni.$uv.toast(`抱歉，最少${str}金额为1`);
    return;
  }
  if (!checkStr(amountVal.value, "number")) {
    uni.$uv.toast(`抱歉，${str}金额请输入整数`);
    return;
  }
  popupRef.value.close();
  modalRef.value.open();
};

//status===2 未接单取消订单
const handleCancel = (item) => {
  uni
    .$showModal({
      title: "",
      content: "是否确定取消订单？",
      confirmVal: "确定",
      cancelVal: "取消",
    })
    .then(() => {
      if (item.status === 2) {
        GetUpdateOrderStatusApi({
          tag: 12,
          orderId: item.orderId,
        }).then((res) => {
          uni.$uv.toast("取消订单成功");
          scrollViewRef.value?.reloadData(initParams);
        });
      } else {
        cancelOrderByOrderId({
          orderId: item.orderId,
        }).then((res) => {
          uni.$uv.toast("取消订单成功");
          scrollViewRef.value?.reloadData(initParams);
        });
      }
    });
};

const formatTime = (createTime) => dayjs().diff(dayjs(createTime), "hour");

//申请验收
const handleClick = (item) => {
  GetOrderIsUploadImg({
    orderId: item.orderId,
  }).then((res) => {
    if (res.data.isFirst * 1 !== 1) {
      uni
        .$showModal({
          title: "",
          content: "该订单未上传首图，请上传后再次申请验收",
          confirmVal: "上传首图",
          cancelVal: "取消",
        })
        .then(() => {
          navigateTo(
            `/pages_orders/order_details/index?active=${initParams.type}&status=${item.status}&afterCreateTime=${item.afterCreateTime}&orderId=${item.orderId}`
          );
        });
      return;
    }
    navigateTo(
      //type=1 上传验收 //type=2 上传首图
      `/pages_orders/order_details/upload?type=1&orderId=${item.orderId}&active=${initParams.type}&status=${initParams.status}`
    );
  });
};

//同意验收
const handleAgree = (item) => {
  if (!isRealName_SetPwd()) return;
  modelType.value = "同意验收";
  orderId.value = item.orderId;
  payPwd.value = "";
  uni
    .$showModal({
      title: "",
      content: "是否同意验收？",
      confirmVal: "同意",
      cancelVal: "取消",
    })
    .then(() => {
      modalRef.value.open();
    });
};

//支付密码
const handleSubmit = () => {
  const MD5_PWD = Md5(payPwd.value);
  switch (modelType.value) {
    case "同意撤销":
      uni.$uv.throttle(() => {
        GetUpdateOrderStatusApi({
          tag: 11,
          orderId: orderId.value,
          password: MD5_PWD,
        }).then((res) => {
          modalRef.value.close();
          uni.$uv.toast("同意撤销成功");
          setTimeout(() => {
            scrollViewRef.value?.reloadData(initParams);
          }, 500);
        });
      }, 1000);
      break;
    case "同意验收":
      uni.$uv.throttle(() => {
        GetUpdateOrderStatusApi({
          tag: 6,
          orderId: orderId.value,
          password: MD5_PWD,
        }).then((res) => {
          modalRef.value.close();
          uni.$uv.toast("同意验收成功");
          setTimeout(() => {
            scrollViewRef.value?.reloadData(initParams);
          }, 500);
        });
      }, 1000);

      break;
    case "加价":
      uni.$uv.throttle(() => {
        AddOrderAmountApi({
          amount: amountVal.value,
          orderId: orderId.value,
          password: MD5_PWD,
        }).then((res) => {
          modalRef.value.close();
          uni.$uv.toast("加价成功");
          setTimeout(() => {
            scrollViewRef.value?.reloadData(initParams);
            amountVal.value = "";
          }, 500);
        });
      }, 1000);
      break;
    case "去支付":
      uni.$uv.throttle(() => {
        ConfirmPaymentApi({
          orderNo: orderNo.value,
          password: MD5_PWD,
        }).then((res) => {
          modalRef.value.close();
          uni.$uv.toast("支付成功");
          setTimeout(() => {
            scrollViewRef.value?.reloadData(initParams);
          }, 500);
        });
      }, 1000);
      break;
    case "打赏打手": //
      uni.$uv.throttle(() => {
        RaisePriceApi({
          orderNo: orderNo.value,
          tag: 2,
          password: MD5_PWD,
          amount: amountVal.value,
        }).then((res) => {
          uni.$uv.toast("打赏打手成功");
          modalRef.value.close();
          setTimeout(() => {
            scrollViewRef.value?.reloadData(initParams);
            amountVal.value = "";
          }, 500);
        });
      }, 1000);
      break;
  }
};

//操作订单
const actions = computed(() => {
  if (!orderStatus.value) return [];

  let actionList = [];

  const baseActions = [
    {
      name: "申请撤销",
      callback: () => {
        navigateTo(
          `/pages_orders/withdrawal_of_appeal/index?orderId=${orderId.value}&active=${initParams.type}&amount=${acceptParams.amount}&cashDeposit=${acceptParams.cashDeposit}&pageType=1&status=${initParams.status}`
        );
      },
    },
  ];

  //撤销中  同意撤销
  const ConsentRevocationActions = [
    {
      name: "同意撤销",
      callback: () => {
        if (!isRealName_SetPwd()) return;
        modelType.value = "同意撤销";
        payPwd.value = "";
        let temp = `同意撤销后您将\r\n收入`;
        if (initParams.type === 2) {
          temp =
            temp +
            `代练费${payVicarious.value}元 支出保证金${compensation.value}元`;
        } else {
          temp =
            temp +
            `保证金${compensation.value}元 支出代练费${payVicarious.value}元`;
        }
        uni
          .$showModal({
            title: "提示",
            content: temp,
            confirmVal: "同意",
            cancelVal: "取消",
            customStyle: {
              title: {
                // 使用 CSS 来设置样式
                "font-weight": "bold",
              },
            },
          })
          .then(() => {
            modalRef.value.open();
          });
      },
    },
  ];

  //撤销中  申请仲裁
  const ArbitrationActions = [
    {
      name: "申请仲裁",
      callback: () => {
        // 申请撤销开始一小时后打手才可以申请仲裁

        const curTime = dayjs();
        const tarTime = dayjs(afterCreateTime.value);
        const now = curTime.diff(tarTime) / (1000 * 60 * 60);

        if (now < 1) {
          uni.$uv.toast("一小时后才能申请仲裁");
          return;
        }
        uni
          .$showModal({
            title: "提示",
            content: "订单是否申请平台官方客服介入，为您公正处理。",
            confirmVal: "确定",
            cancelVal: "取消",
          })
          .then(() => {
            GetUpdateOrderStatusApi({
              tag: 5,
              orderId: orderId.value,
              orderAfterSale: {
                orderId: orderId.value,
                type: 2, //申请类型 1 撤销 2 仲裁 3 提交异常
              },
            }).then((res) => {
              uni.$uv.toast("申请仲裁成功,请等待审核结果..");
              setTimeout(() => {
                scrollViewRef.value?.reloadData(initParams);
              }, 500);
            });
          });
      },
    },
  ];

  //免押金申请仲裁
  const isNoDepositArbitrationActions = [
    {
      name: "申请仲裁",
      callback: () => {
        uni
          .$showModal({
            title: "提示",
            content: "订单是否申请平台官方客服介入，为您公正处理。",
            confirmVal: "确定",
            cancelVal: "取消",
          })
          .then(() => {
            GetUpdateOrderStatusApi({
              tag: 5,
              orderId: orderId.value,
              orderAfterSale: {
                orderId: orderId.value,
                type: 2, //申请类型 1 撤销 2 仲裁 3 提交异常
              },
            }).then((res) => {
              uni.$uv.toast("申请仲裁成功,请等待审核结果..");
              setTimeout(() => {
                scrollViewRef.value?.reloadData(initParams);
              }, 500);
            });
          });
      },
    },
  ];

  //验收中   取消验收
  const InacceptanceActions = [
    {
      name: "取消验收",
      callback: () => {
        uni
          .$showModal({
            title: "",
            content: "确定要取消验收？",
            confirmVal: "确定",
            cancelVal: "取消",
          })
          .then(() => {
            GetUpdateOrderStatusApi({
              tag: 13,
              orderId: orderId.value,
            }).then((res) => {
              uni.$uv.toast("取消验收成功");
              setTimeout(() => {
                scrollViewRef.value?.reloadData(initParams);
              }, 500);
            });
          });
      },
    },
  ];

  //是否是免押金的订单  是则申请撤销变成申请仲裁 否则是申请撤销
  const isNoDepositCallback =
    orderItem.value.isNoDeposit === 2
      ? isNoDepositArbitrationActions
      : baseActions;

  //开始判断按钮
  switch (orderStatus.value) {
    case 3: //代练中
      if (initParams.type === 2) {
        actionList = [
          ...isNoDepositCallback,
          {
            name: "申请异常",
            callback: () => {
              navigateTo(
                `/pages_orders/complaint_exception/index?orderId=${orderId.value}`
              );
            },
          },
        ];
      } else {
        actionList = isNoDepositCallback;
      }

      break;
    case 5: //异常中
      if (initParams.type === 2) {
        actionList = [
          ...isNoDepositCallback,
          {
            name: "取消异常",
            callback: () => {
              uni
                .$showModal({
                  title: "",
                  content: "确定要取消异常？",
                  confirmVal: "确定",
                  cancelVal: "取消",
                })
                .then(() => {
                  GetUpdateOrderStatusApi({
                    tag: 7,
                    orderId: orderId.value,
                  }).then((res) => {
                    uni.$uv.toast("取消异常成功");
                    setTimeout(() => {
                      scrollViewRef.value?.reloadData(initParams);
                    }, 500);
                  });
                });
            },
          },
        ];
      } else {
        actionList = [
          ...isNoDepositCallback,
          {
            name: "申请协商",
            callback: () => {
              navigateTo(
                `/pages_orders/message_board/index?id=${orderId.value}&status=${orderStatus.value}&hatchetUserId=${hatchetUserId.value}`
              );
            },
          },
        ];
      }
      break;
    case 6: //撤销中
      if (applyRepeal.value === userInfo.id) {
        actionList = [
          {
            name: "取消撤销",
            callback: () => {
              uni
                .$showModal({
                  title: "",
                  content: "确定要取消撤销？",
                  confirmVal: "确定",
                  cancelVal: "取消",
                })
                .then(() => {
                  GetUpdateOrderStatusApi({
                    tag: 8,
                    orderId: orderId.value,
                  }).then((res) => {
                    uni.$uv.toast("取消撤销成功");
                    setTimeout(() => {
                      scrollViewRef.value?.reloadData(initParams);
                    }, 500);
                  });
                });
            },
          },
          ...ArbitrationActions,
        ];
      } else {
        actionList = [
          ...ConsentRevocationActions, //同意撤销
          ...ArbitrationActions, //申请仲裁
        ];
      }
      break;

    case 7: // 仲裁中     upStatus 0 否 1是
      //申请仲裁发起方userid applyArbitrament   //申请撤销发起方userid applyRepeal

      // console.log('仲裁申请的id：', applyArbitrament.value)
      // console.log('撤销申请的id：', applyRepeal.value)
      // console.log('当前用户id：', userInfo.id)
      // console.log('有撤销记录：', upStatus.value)

      if (applyArbitrament.value === userInfo.id) {
        actionList = [
          {
            name: "取消仲裁",
            callback: () => {
              uni
                .$showModal({
                  title: "",
                  content: "确定要取消仲裁？",
                  confirmVal: "确定",
                  cancelVal: "取消",
                })
                .then(() => {
                  GetUpdateOrderStatusApi({
                    tag: 9,
                    orderId: orderId.value,
                  }).then((res) => {
                    uni.$uv.toast("取消仲裁成功");
                    setTimeout(() => {
                      scrollViewRef.value?.reloadData(initParams);
                    }, 500);
                  });
                });
            },
          },
        ];
      }

      if (upStatus.value === 1 && applyRepeal.value !== userInfo.id) {
        actionList.push(...ConsentRevocationActions); //同意撤销
      }
      break;
    case 4: // 待验收
      if (initParams.type === 2) {
        actionList = [
          ...isNoDepositCallback,
          ...InacceptanceActions, //取消验收
        ];
      } else {
        actionList = isNoDepositCallback;
      }
      break;
  }
  return actionList;
});
const orderItem = ref(); //点击订单列表的信息
const showOrderSelect = (item, type) => {
  acceptParams.amount = initParams.type == 3 ? item.amount : item.orderAmount; //代练费
  acceptParams.cashDeposit = item.cashDeposit; //保证金
  afterCreateTime.value = item.afterCreateTime; //申请撤销的时间
  orderStatus.value = item.status; //订单状态
  orderId.value = item.orderId; //订单ID
  upStatus.value = item.upStatus; //是否有撤销记录
  hatchetUserId.value = item.hatchetUserId; //打手id
  applyArbitrament.value = item.applyArbitrament; //申请仲裁发起方userid
  applyRepeal.value = item.applyRepeal; //申请撤销发起方userid
  compensation.value = item.compensation; //
  payVicarious.value = item.payVicarious; //
  orderItem.value = item;
  if (actions.value.length > 0) {
    orderSelectRef.value.open();
  }
};
//订单页面操作
const actionSheetSelect = (item) => {
  item.callback();
};

const handleChange = (item) => {
  initParams.status = item.status;
  curIndex.value = item.index;
  uni.$uv.debounce(
    () => {
      //	获取列表
      scrollViewRef.value?.reloadData(initParams);
    },
    500,
    false
  );
};

const scrollViewRef = ref();

const getOrderInfo = (data) => {
  dataList.value = data;
};

const isShowDot = ref(false);

async function getDotInfo() {
  const msg = await GetMsgReadDotApi();
  const inform = await GetInformReadDotApi();
  if (msg.data || inform.data) {
    isShowDot.value = true;
  } else {
    isShowDot.value = false;
  }
}

//	防止接口多次调用
const onShowFlag = ref(0);
onShow(() => {

    scrollViewRef.value?.reloadData(initParams);
    getDotInfo();
    //订单待付款查看详情使用
    if (props.active) {
      initParams.type = props.active * 1;
    }
});

onLoad((option) => {
  if (option.active) {
    activeCurrent.value = option.active - 2;
  }
});

//跳转
function navigateTo(url) {
  uni.navigateTo({
    url,
  });
}

// 	键盘高度变化事件
const KeyboardHeight = ref(true);
// #ifndef H5
uni.onKeyboardHeightChange((res) => {
  KeyboardHeight.value = res.height * 1 === 0;
  emit("onKeyboardHeightChange", KeyboardHeight.value);
});
// #endif
</script>


